import Util from './util'
import * as Cesium from 'cesium/Cesium'


//创建一个div，用来做3d的盒子
const _div = document.createElement('div');
_div.id = 'cesiumDiv';
_div.style.display = 'none';
_div.style.position = 'absolute';
_div.style.width = '100%';
_div.style.height = '100%';
_div.style.overflow = 'hidden';
document.body.appendChild(_div);

let cesiumViewer = new Cesium.Viewer('cesiumDiv', {
  baseLayerPicker: false,
  animation: false,
  timeline: false,
  homeButton: true,
  infoBox: false,
  sceneModePicker: false,
  navigationHelpButton: false,
  navigationInstructionsInitiallyVisible: false,
  fullscreenButton: false,
  geocoder: false,
  selectionIndicator: false,
  shouldAnimate: true,
  scene3DOnly: true,
  imageryProvider: new Cesium.SingleTileImageryProvider({
    url: './world.jpg'
  })

});

cesiumViewer.imageryLayers.get(0).brightness = 1.6;
for (let i = 0; i < cesiumViewer.imageryLayers.length; i++) {
  cesiumViewer.imageryLayers.get(i).imageryProvider.errorEvent.addEventListener(function () {});
}


// cesiumViewer.scene.logarithmicDepthBuffer = false;
cesiumViewer.scene.sun.destroy();
cesiumViewer.scene.sun = undefined;
cesiumViewer.scene.moon.destroy();
cesiumViewer.scene.moon = undefined;
cesiumViewer.scene.skyAtmosphere.show = false;
if(cesiumViewer.fullscreenButton){
  let fullscreenContainer = cesiumViewer.container.querySelector('.cesium-viewer-fullscreenContainer');
  if (fullscreenContainer) {
    fullscreenContainer.style.left = '0px';
    fullscreenContainer.style.cssText += ';width: 32px;height: 32px;top:10px !important; margin-top: 4px; margin-right: 3px;margin-bottom: 2px;margin-left: 13px;';
    let cesiumviewertoolbar = cesiumViewer.container.querySelector('.cesium-viewer-toolbar');
    cesiumviewertoolbar.style.cssText += 'left: 0px;margin: 8px 3px 2px 10px;top: 39px !important;';

    let fullscreenbtn = fullscreenContainer.querySelector('.cesium-fullscreenButton');
    if(fullscreenbtn){
      fullscreenbtn.style.cssText += ';background: #fff;border: 1px solid #444;color: #666;fill: #666;';
    }

  }
}
let animationContainer = cesiumViewer.container.querySelector('.cesium-viewer-animationContainer');
if(animationContainer) {
  animationContainer.style.bottom = '60px';
}
let timelineContainer = cesiumViewer.container.querySelector('.cesium-viewer-timelineContainer');
if(timelineContainer){
  timelineContainer.style.bottom = '50px';
  timelineContainer.style.height = '40px';
  timelineContainer.style.right = '0px';
}
cesiumViewer.scene.highDynamicRange = false;
cesiumViewer.scene.globe.enableLighting = false;
cesiumViewer.scene.globe.dynamicAtmosphereLighting = false;

let flashlight = new Cesium.DirectionalLight({
  direction: cesiumViewer.scene.camera.directionWC, // Updated every frame
  intensity: 1.0
});
cesiumViewer.scene.light = flashlight;
cesiumViewer.scene.preRender.addEventListener(function(scene)  {
  scene.light.direction = Cesium.Cartesian3.clone(scene.camera.directionWC,
    scene.light.direction);

});

// cesiumViewer.scene.debugShowFramesPerSecond = true;
// cesiumViewer.scene.skyAtmosphere.show = true;
cesiumViewer.scene.globe.depthTestAgainstTerrain = false;
cesiumViewer._cesiumWidget._creditContainer.style.display = "none"; //去除左下角LOGO

// viewer._cesiumWidget._supportsImageRenderingPixelated = Cesium.FeatureDetection.supportsImageRenderingPixelated();
// viewer._cesiumWidget._forceResize = true;
// if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
//     let vtxf_dpr = window.devicePixelRatio;
//     // 适度降低分辨率
//     while (vtxf_dpr >= 2.0) {
//         vtxf_dpr /= 2.0;
//     }
//     //alert(dpr);
//     viewer.resolutionScale = vtxf_dpr;
// }

cesiumViewer.scene.pickTranslucentDepth = false;
cesiumViewer.scene.postProcessStages.fxaa.enabled = true;// 关闭fxaa，使文字清晰
cesiumViewer.scene.screenSpaceCameraController.zoomEventTypes = [Cesium.CameraEventType.WHEEL, Cesium.CameraEventType.PINCH]; //add by wfw
cesiumViewer.scene.screenSpaceCameraController.tiltEventTypes = [Cesium.CameraEventType.PINCH, Cesium.CameraEventType.RIGHT_DRAG]; //add by wfw

// cesiumViewer.camera.setView({
//     destination: Cesium.Rectangle.fromDegrees(40.0, -15.0, 180.0, 80.0)
//
// })
// cesiumViewer.homeButton.viewModel.command.beforeExecute.addEventListener( (e)=> {
//     e.cancel = true;
//     // viewer.camera.lookAt(store.state.sceneCenterCartesian, new Cesium.HeadingPitchRange(0.0, Cesium.Math.toRadians(-45.0), 1200));
//     // viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
//     cesiumViewer.camera.setView({
//         destination: Cesium.Rectangle.fromDegrees(40.0, -15.0, 180.0, 80.0)
//
//     })
// });


//汉化
//     viewer.sceneModePicker.viewModel.duration = 0.0;//去掉二三维切换动画效果
//     if (viewer.sceneModePicker) {
//         viewer.sceneModePicker.viewModel.tooltip3D = "三维";
//         viewer.sceneModePicker.viewModel.tooltip2D = "二维";
//         viewer.sceneModePicker.viewModel.tooltipColumbusView = "哥伦布视图";
//     }
if (cesiumViewer.homeButton) {
  cesiumViewer.homeButton.viewModel.tooltip = "厂区定位";
  let homebtn = cesiumViewer.container.querySelector('.cesium-home-button');
  if(homebtn){
    homebtn.style.cssText += ';background: #fff;border: 1px solid #444;color: #666;fill: #666;';
  }
}
if (cesiumViewer.navigationHelpButton) {
  cesiumViewer.navigationHelpButton.viewModel.tooltip = "操作指南";
  let clickHelper = cesiumViewer.navigationHelpButton.container.getElementsByClassName("cesium-click-navigation-help")[0];
  let touchHelper = cesiumViewer.navigationHelpButton.container.getElementsByClassName("cesium-touch-navigation-help")[0];
  let button = cesiumViewer.navigationHelpButton.container.getElementsByClassName("cesium-navigation-button-right")[0];
  button.innerHTML = button.innerHTML.replace(">Touch", ">手势");
  button = cesiumViewer.navigationHelpButton.container.getElementsByClassName("cesium-navigation-button-left")[0];
  button.innerHTML = button.innerHTML.replace(">Mouse", ">鼠标");
  let click_help_pan = clickHelper.getElementsByClassName("cesium-navigation-help-pan")[0];
  click_help_pan.innerHTML = "平移";
  let click_help_pan_details = click_help_pan.parentNode.getElementsByClassName("cesium-navigation-help-details")[0];
  click_help_pan_details.innerHTML = "按下左键 + 拖动";
  let click_help_zoom = clickHelper.getElementsByClassName("cesium-navigation-help-zoom")[0];
  click_help_zoom.innerHTML = "旋转";
  click_help_zoom.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "按下右键+拖动";
  click_help_zoom.parentNode.getElementsByClassName("cesium-navigation-help-details")[1].innerHTML = "";
  let click_help_rotate = clickHelper.getElementsByClassName("cesium-navigation-help-rotate")[0];
  click_help_rotate.innerHTML = "缩放";
  click_help_rotate.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "滚动鼠标滚轮";
  click_help_rotate.parentNode.getElementsByClassName("cesium-navigation-help-details")[1].innerHTML = "";
  //触屏操作
  let touch_help_pan = touchHelper.getElementsByClassName("cesium-navigation-help-pan")[0];
  touch_help_pan.innerHTML = "平移";
  touch_help_pan.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "单指拖动";
  let touch_help_zoom = touchHelper.getElementsByClassName("cesium-navigation-help-zoom")[0];
  touch_help_zoom.innerHTML = "缩放";
  touch_help_zoom.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "双指捏合";
  let touch_help_tilt = touchHelper.getElementsByClassName("cesium-navigation-help-rotate")[0];
  touch_help_tilt.innerHTML = "俯仰";
  touch_help_tilt.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "双指同向拖动";
  let touch_help_rotate = touchHelper.getElementsByClassName("cesium-navigation-help-tilt")[0];
  touch_help_rotate.innerHTML = "旋转";
  touch_help_rotate.parentNode.getElementsByClassName("cesium-navigation-help-details")[0].innerHTML = "双指反向拖动";
}

// cesiumViewer.scene.skyBox =  new Cesium.SkyBox({
//         show: false
//     });
let statusbarEnable = true;
let handler = new Cesium.ScreenSpaceEventHandler(cesiumViewer.scene.canvas)
if (statusbarEnable) {
  let statusbarstr = '<div id="latlng_show" style="width: 100%;height: 5%;position: absolute;bottom: 40px;z-index: 3;font-size: 15px;color: #e9e9e9;text-shadow: 2px 2px 2px #000;background-color: rgba(0,0,0,.4);">' +
    '<div style="width: 10%;height: 3%;float: left; margin-top: 4px;">' +
    '<font color="white" size="3"> 帧率：<span id="framerate_show"> </span> </font>' +
    '</div>' +
    '<div style="width: 15%;height: 3%;float: left; margin-top: 4px;">' +
    '<font color="white" size="3"> 经度：<span id="longitude_show"> </span> </font>' +
    '</div>' +
    '<div style="width: 15%;height: 3%;float: left; margin-top: 4px;">' +
    '<font color="white" size="3"> 纬度：<span id="latitude_show"> </span> </font>' +
    '</div>' +
    '<div style="width: 12%;height: 3%;float: left; margin-top: 4px;">' +
    '<font color="white" size="3"> 高程：<span id="altitude_show"> </span> m</font>' +
    '</div>' +
    '<div style="width: 15%;height: 3%;float: left; margin-top: 4px;">' +
    ' <font color="white" size="3"> 偏航：<span id="heading_show"> </span> </font>' +
    ' </div>' +
    '<div style="width: 13%;height: 3%;float: left; margin-top: 4px;">' +
    ' <font color="white" size="3"> 俯仰：<span id="pitch_show"> </span> </font>' +
    '</div>' +
    '<div id="camaltitude" style="width: 20%;height: 3%;float: left; margin-top: 4px;">' +
    '<font color="white" size="3"> 相机高度：<span id="camaltitude_show"> </span> km</font>' +
    '</div>' +
    '</div>'



  Util.append(cesiumViewer.container, statusbarstr)


  let framerate = cesiumViewer.container.querySelector('#framerate_show')
  let lonEle = cesiumViewer.container.querySelector('#longitude_show')
  let latEle = cesiumViewer.container.querySelector('#latitude_show')
  let altEle = cesiumViewer.container.querySelector('#altitude_show')
  let headingEle = cesiumViewer.container.querySelector('#heading_show')
  let pitchEle = cesiumViewer.container.querySelector('#pitch_show')
  let camaltitudeEle = cesiumViewer.container.querySelector('#camaltitude_show')

  let _lastFpsSampleTime = Cesium.getTimestamp()
  let _fpsFrameCount = 0
  cesiumViewer.scene.postRender.addEventListener(function () {
    let time = Cesium.getTimestamp()
    _fpsFrameCount++
    let fpsElapsedTime = time - _lastFpsSampleTime
    if (fpsElapsedTime > 1000) {
      let fps = 'N/A'
      fps = _fpsFrameCount * 1000 / fpsElapsedTime | 0
      framerate.innerHTML = fps
      _lastFpsSampleTime = time
      _fpsFrameCount = 0
    }
  })



  //let cartesian = null;

  cesiumViewer.screenSpaceEventHandler.setInputAction(function(movement) {


    // try {
    //      cartesian = cesiumViewer.scene.pickPosition(movement.endPosition)
    // } catch(e) {
    //   e
    //     let pick = new Cesium.Cartesian2(movement.endPosition.x, movement.endPosition.y);
    //      cartesian = cesiumViewer.scene.globe.pick(cesiumViewer.camera.getPickRay(pick), cesiumViewer.scene);
    //
    // }
    if (!Cesium.defined(movement.endPosition)) return;
    let pick = new Cesium.Cartesian2(movement.endPosition.x, movement.endPosition.y);
    let cartesian = cesiumViewer.scene.globe.pick(cesiumViewer.camera.getPickRay(pick), cesiumViewer.scene);
    if (!Cesium.defined(cartesian)) return
    let cartographic = cesiumViewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian)
    let lat_String = Cesium.Math.toDegrees(cartographic.latitude).toFixed(4)
    let log_String = Cesium.Math.toDegrees(cartographic.longitude).toFixed(4)
    let alti_String = cartographic.height > 0 ? cartographic.height.toFixed(2) : '0'
    lonEle.innerHTML = log_String + '°'
    latEle.innerHTML = lat_String + '°'
    altEle.innerHTML = alti_String


  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

  cesiumViewer.camera.changed.addEventListener(function() {

    let camaltitude_String = (cesiumViewer.camera.positionCartographic.height / 1000).toFixed(2)
    let heading_String = Cesium.Math.toDegrees(cesiumViewer.camera.heading).toFixed(2)
    let pitch_String = (Cesium.Math.toDegrees(cesiumViewer.camera.pitch) + 90).toFixed(2)

    headingEle.innerHTML = heading_String + '°'
    pitchEle.innerHTML = pitch_String + '°'
    camaltitudeEle.innerHTML = camaltitude_String

  })
}
//防止进入地下
let enableTilt = true
cesiumViewer.scene.screenSpaceCameraController.minimumZoomDistance = 22
cesiumViewer.clock.onTick.addEventListener(function() {
  setMinCamera()
})
let setMinCamera = function() {
  if (cesiumViewer.camera.pitch > 0) {
    cesiumViewer.scene.screenSpaceCameraController.enableTilt = false
  }
}
let startMousePosition;
let mousePosition;
handler.setInputAction(function(movement) {

  mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position)
  handler.setInputAction(function(movement) {
    mousePosition = movement.endPosition
    let y = mousePosition.y - startMousePosition.y
    if (y > 0) {
      cesiumViewer.scene.screenSpaceCameraController.enableTilt = true
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

}, Cesium.ScreenSpaceEventType.RIGHT_DOWN)




window.initSceneData = false;
window.cesiumViewer = cesiumViewer;
